var layer = layui.layer,
    layForm = layui.form,
    laytpl = layui.laytpl;

var FormCommon = {
    /**
     *
     * @param url
     * @param subId sub
     * @param index
     * @param editData function 修改数据的方法，参数：data 表单内的所有数据
     * @param afterCommit function 提交表单后的回调函数(成功才会调用)
     *
     */
    initForm: function (param) {
        if (!param || !param.url) {
            layer.msg("url不能为空!");
        }
        var defaultParam = {
            url: "",
            subId: "sub",
            subContentType: "form",
            editData: function (data) {
                return data;
            },
            afterCommit: function (res) {
                FormCommon.closeDialog();
            }
        };
        //合并参数，替换前者中相同的参数
        $.extend(defaultParam, param);
        //信息验证
        var moneyReg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        layForm.verify({
            money: function (value, item) { //value：表单的值、item：表单的DOM对象
                if (!moneyReg.test(value)) {
                    return '请输入正确的金额！';
                }
            }
        });
        var subFlag = false;
        layForm.on('submit(' + defaultParam.subId + ')', function (data) {
            var contentType,
                formData;
            if (defaultParam.subContentType == "json") {
                try {
                    formData = JSON.stringify(defaultParam.editData(data.field));
                } catch (e) {
                    console.log(e);
                    if (typeof(e) == "string") {
                        layer.msg(e, {icon: 5});
                    }
                   return false;
                }
                contentType = "application/json;charset=utf-8";
            } else {
                formData = defaultParam.editData(data.field);
                contentType = "application/x-www-form-urlencoded";
            }
            if (!subFlag) {
                subFlag = true;
                $.ajax({
                    type: 'post',
                    url: defaultParam.url,
                    data: formData,
                    contentType: contentType,
                    success: function (res) {
                        if (res.code != 1) {
                            subFlag = false;
                            if (res.data instanceof Array) {
                                $.each(res.data, function (index, value) {
                                    layer.msg(value.errorMsg);
                                });
                            } else if (typeof(res.data) != "undefined" && res.data.length > 0) {
                                layer.msg(res.data, {icon: 5});
                            } else {
                                layer.msg(res.message, {icon: 5});
                            }
                        } else {
                            layer.msg('操作成功！', {
                                icon: 1,
                                time: 1000 //2秒关闭（如果不配置，默认是3秒）
                            }, function () {
                                defaultParam.afterCommit(res);
                            });
                        }
                    },
                    error: function (res) {
                        subFlag = false;
                        layer.msg("操作异常", {icon: 5});
                    }
                });
            }
            return false;
        });
    },
    closeDialog: function () {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
        parent.$table.bootstrapTable('refresh');
    },
    //生成不重复id
    generateRandomAlphaNum: function (len) {
        var rdmString = "";
        for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
        return rdmString.substr(0, len);
    }
};

